package com.example.flashApp.usage

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.flashApp.databinding.ItemUsageStatBinding
import java.text.SimpleDateFormat
import java.util.Locale

class UsageStatsAdapter : ListAdapter<UsageStat, UsageStatsAdapter.UsageStatViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsageStatViewHolder {
        val binding = ItemUsageStatBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return UsageStatViewHolder(binding)
    }

    override fun onBindViewHolder(holder: UsageStatViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class UsageStatViewHolder(
        private val binding: ItemUsageStatBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())

        fun bind(usageStat: UsageStat) {
            binding.apply {
                packageName.text = usageStat.packageName
                duration.text = formatDuration(usageStat.duration)
                lastUsed.text = dateFormat.format(usageStat.lastUsed)
            }
        }

        private fun formatDuration(millis: Long): String {
            val seconds = millis / 1000
            val hours = seconds / 3600
            val minutes = (seconds % 3600) / 60
            return String.format("%02d:%02d:%02d", hours, minutes, seconds % 60)
        }
    }

    private class DiffCallback : DiffUtil.ItemCallback<UsageStat>() {
        override fun areItemsTheSame(oldItem: UsageStat, newItem: UsageStat): Boolean {
            return oldItem.packageName == newItem.packageName
        }

        override fun areContentsTheSame(oldItem: UsageStat, newItem: UsageStat): Boolean {
            return oldItem == newItem
        }
    }
}
